import api from './index'

// 获取API基础URL
const API_BASE_URL = 'http://localhost:8000'

export interface AgentStatusResponse {
  agent: string
  llm_available: boolean
  browser_available: boolean
  features: string[]
  // 部分环境可能返回 redis 状态（例如 /health），在 /agent/status 中通常不存在
  redis?: string
}

export interface ChatResponse {
  message: string
  session_id: string
  timestamp: string
}

export interface Session {
  id: string
  name: string
  created_time: string
}

export interface SessionsResponse {
  sessions: Session[]
  count: number
}

export interface FileInfo {
  id: string
  original_name: string
  saved_name: string
  file_path: string
  size: number
  upload_time: string
  used: boolean
}

export interface FileListResponse {
  session_id: string
  files: FileInfo[]
  count: number
}

export interface UsingFilesResponse {
  session_id: string
  using_files: FileInfo[]
  count: number
}

export interface FileOperationResponse {
  status: string
  message: string
}

export interface BatchOperationResponse {
  status: string
  message: string
  results: Array<{
    file_id: string
    success: boolean
    file_name: string
  }>
}

export interface FileDetailResponse {
  file_info: FileInfo
  parse_info: {
    file_id: string
    original_name: string
    file_extension: string
    is_supported: boolean
    file_size: number
    formatted_size: string
    can_parse_content: boolean
  }
}

export const sendMessage = async (
  message: string,
  sessionId: string = 'default'
): Promise<ChatResponse> => {
  // axios 响应拦截器已返回 response.data
  return (await api.post('/chat', {
    message,
    session_id: sessionId
  })) as ChatResponse
}

export interface StreamChunk {
  chunk: string
  type: 'content' | 'error' | 'done' | 'start'
  timestamp?: string
}

// 存储活跃的流式请求控制器
const activeStreamControllers = new Map<string, AbortController>()

export const sendMessageStream = async (
  message: string,
  sessionId: string = 'default',
  onChunk?: (chunk: StreamChunk) => void,
  onError?: (error: string) => void,
  onComplete?: (timestamp?: string) => void,
  onStart?: () => void
): Promise<void> => {
  // 创建AbortController用于中断请求
  const controller = new AbortController()
  activeStreamControllers.set(sessionId, controller)

  try {
    const response = await fetch(`${api.defaults.baseURL}/chat/stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        message,
        session_id: sessionId
      }),
      signal: controller.signal
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法获取响应流')
    }

    const decoder = new TextDecoder()
    let buffer = ''

    while (true) {
      const { done, value } = await reader.read()
      
      if (done) break

      buffer += decoder.decode(value, { stream: true })
      
      // 处理SSE数据
      const lines = buffer.split('\n')
      buffer = lines.pop() || '' // 保留不完整的行

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.slice(6)) as StreamChunk
            
            if (data.type === 'done') {
              onComplete?.(data.timestamp)
              return
            } else if (data.type === 'error') {
              onError?.(data.chunk)
              return
            } else if (data.type === 'start') {
              onStart?.()
            } else if (data.type === 'content') {
              onChunk?.(data)
            }
          } catch (e) {
            console.error('解析SSE数据失败:', e)
          }
        }
      }
    }
  } catch (error) {
    if (error instanceof Error && error.name === 'AbortError') {
      // 请求被中断，这是正常的停止操作
      console.log('流式请求已被中断')
      onComplete?.()
    } else {
      console.error('流式请求失败:', error)
      onError?.(error instanceof Error ? error.message : '未知错误')
    }
  } finally {
    // 清理控制器
    activeStreamControllers.delete(sessionId)
  }
}

export const stopGeneration = async (sessionId: string): Promise<void> => {
  try {
    // 1. 首先中止前端流式请求
    const controller = activeStreamControllers.get(sessionId)
    if (controller) {
      controller.abort()
      activeStreamControllers.delete(sessionId)
    }

    // 2. 通知后端停止生成 - 使用正确的API端点
    const response = await fetch(`${API_BASE_URL}/api/chat/stop/${sessionId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    })

    if (!response.ok) {
      const errorText = await response.text()
      console.warn(`停止生成请求失败: ${response.status} - ${errorText}`)
      throw new Error(`停止生成失败: ${response.status}`)
    }

    const result = await response.json()
    console.log('停止生成响应:', result)
  } catch (error) {
    console.error('停止生成时出错:', error)
    // 重新抛出错误，让调用方处理
    throw error
  }
}

export const stopAllGenerations = async (): Promise<void> => {
  try {
    // 1. 首先中止所有前端流式请求
    for (const [sessionId, controller] of activeStreamControllers.entries()) {
      controller.abort()
    }
    activeStreamControllers.clear()

    // 2. 通知后端停止所有生成 - 使用正确的API端点
    const response = await fetch(`${API_BASE_URL}/api/chat/stop_all`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    })

    if (!response.ok) {
      console.warn(`停止所有生成请求失败: ${response.status}`)
    }
  } catch (error) {
    console.error('停止所有生成时出错:', error)
  }
}

export interface ChatHistoryResponse {
  session_id: string
  redis_history: Array<{
    // 旧格式字段（向后兼容）
    user?: string
    assistant?: string
    timestamp?: string
    // 新格式字段
    type?: 'user' | 'assistant'
    user_timestamp?: string
    assistant_timestamp?: string
  }>
  agent_history: any[]
}

export interface CreateSessionResponse {
  status: string
  session_id: string
  message: string
}

export const getChatHistory = async (sessionId: string): Promise<ChatHistoryResponse> => {
  return (await api.get(`/sessions/${sessionId}`)) as ChatHistoryResponse
}

export const clearSession = (sessionId: string) => {
  return api.delete(`/sessions/${sessionId}`)
}

export const getSessions = async (): Promise<SessionsResponse> => {
  return (await api.get('/sessions')) as SessionsResponse
}

export const createSession = async (): Promise<CreateSessionResponse> => {
  return (await api.post('/sessions')) as CreateSessionResponse
}

export const updateSession = async (sessionId: string, name: string) => {
  return api.put(`/sessions/${sessionId}`, { name })
}

export const uploadFile = (file: File, sessionId: string = 'default') => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('session_id', sessionId)
  return api.post('/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 文件管理相关API
export const getSessionFiles = async (sessionId: string): Promise<FileListResponse> => {
  return (await api.get(`/upload/files/${sessionId}`)) as FileListResponse
}

export const getUsingFiles = async (sessionId: string): Promise<UsingFilesResponse> => {
  return (await api.get(`/upload/using/${sessionId}`)) as UsingFilesResponse
}

export const markFileForUse = async (sessionId: string, fileId: string): Promise<FileOperationResponse> => {
  return (await api.post(`/upload/use/${sessionId}/${fileId}`)) as FileOperationResponse
}

export const unmarkFileForUse = async (sessionId: string, fileId: string): Promise<FileOperationResponse> => {
  return (await api.delete(`/upload/use/${sessionId}/${fileId}`)) as FileOperationResponse
}

export const deleteFile = async (sessionId: string, fileId: string): Promise<FileOperationResponse> => {
  return (await api.delete(`/upload/files/${sessionId}/${fileId}`)) as FileOperationResponse
}

export const clearSessionFiles = async (sessionId: string): Promise<FileOperationResponse> => {
  return (await api.delete(`/upload/files/${sessionId}`)) as FileOperationResponse
}

export const batchMarkFiles = async (sessionId: string, fileIds: string[]): Promise<BatchOperationResponse> => {
  return (await api.post(`/upload/batch-use/${sessionId}`, { file_ids: fileIds })) as BatchOperationResponse
}

export const batchUnmarkFiles = async (sessionId: string, fileIds: string[]): Promise<BatchOperationResponse> => {
  return (await api.delete(`/upload/batch-use/${sessionId}`, { data: { file_ids: fileIds } })) as BatchOperationResponse
}

export const getFileInfo = async (sessionId: string, fileId: string): Promise<FileDetailResponse> => {
  return (await api.get(`/upload/info/${sessionId}/${fileId}`)) as FileDetailResponse
}

export const getSystemStatus = async (): Promise<AgentStatusResponse> => {
  // axios 响应拦截器已返回 response.data，所以这里直接得到数据对象
  return (await api.get('/agent/status')) as AgentStatusResponse
}

export const searchWeb = (query: string, maxResults: number = 5) => {
  return api.post('/search', { query, max_results: maxResults })
}

export const browseWeb = (url: string) => {
  return api.post('/browse', { url })
}